/*
 * @Descripttion:
 * @Author: liuyu
 * @Date: 2023-12-04 15:44:23
 * @LastEditors: liuyu
 * @LastEditTime: 2023-12-04 15:44:23
 * @FilePath: /app/controller/dict/type.js
 */
'use strict';

const Controller = require('egg').Controller;
class DictDataController extends Controller {
  async show() {
    const { ctx: { service, helper, params } } = this;
    const res = await service.dict.data.show({ dict_id: params.id });
    helper.render(200, res);
  }
  async list() {
    const { ctx } = this;
    const { page, page_size, ...where } = ctx.query;
    const dict_type = ctx.params.type;
    // console.log(dict_type);
    const res = await ctx.service.dict.data.index([], {
      dict_type,
      ...where,
    }, page, page_size);
    const total = await this.app.mysql.get('db1').count('dict_data', {
      dict_type,
      ...where,
    });
    ctx.helper.render(200, {
      data: res,
      total,
    });
  }
  async create() {
    const { ctx: { service, helper, request, params } } = this;
    const body = request.body;
    const dict_type = params.type;
    this.ctx.validate({
      dict_label: { type: 'string', required: true, message: '请输入字典名称' },
      dict_value: { type: 'string', required: true },
    }, body);
    // const userInfo = await service.userAdmin.show({ id: ctx.locals.auth.userAdminBid });
    const showRes = await service.dict.data.show({ dict_label: body.dict_label, dict_type });
    if (showRes) {
      helper.render(422, {}, '字典数据已存在');
      return;
    }
    try {
      await service.dict.data.create({
        dict_type,
        ...body,
      });
      helper.render(200, {}, '添加成功');
    } catch (e) {
      helper.render(422, e, '添加失败');
    }
  }
  async update() {
    const { ctx: { service, helper, params, request } } = this;
    const body = request.body;
    const where = { dict_id: params.id };
    try {
      await service.dict.data.update(body, where);
      helper.render(200, {}, '更新成功');
    } catch (e) {
      helper.render(422, e, '更新失败');
    }
  }
  async delete() {
    const { ctx: { service, helper, params } } = this;
    try {
      await service.dict.data.delete(params.id);
      helper.render(200, {}, '删除成功');
    } catch (e) {
      helper.render(422, e, '删除失败');
    }
  }
}

module.exports = DictDataController;
